/*
 * SunSpotHostApplication.java
 *
 * Created on Jul 21, 2009 4:45:20 PM;
 */
package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.Radiogram;
import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.Connector;

/**
 * Sample Sun SPOT host application
 */
public class SunSpotHostApplication {
	
    //*
	private static final String DATABASE_HOST = "csc453-team03.csc.ncsu.edu";
	private static final String DATABASE_NAME = "test";
	private static final String DATABASE_USERNAME = "sensorsadmin";
	private static final String DATABASE_PASSWORD = "csc453Fri1";
    /*/
    private static final String DATABASE_HOST = "174.120.20.226";
	private static final String DATABASE_NAME = "netmd5cr_spotdatabase";
	private static final String DATABASE_USERNAME = "netmd5cr_spotu";
	private static final String DATABASE_PASSWORD = "AndR%25o9I*"; //*/
	private Connection dbConn;
	private Statement dbStmt;

    private static final long SECONDS = 1000;
    private static final long PAUSE = 4*SECONDS;
    
    private RadiogramConnection cmdConn;
    private RadiogramConnection dataConn;
    private Radiogram xrg;
    private static final String CMD_PORT = "87";
    private static final String DATA_PORT = "89";
    
    private boolean running = true;

    private Thread pollThread = new Thread() {
        public void run() {
            while (running) {
                try {
                    xrg.reset();
                    xrg.writeBoolean(true);
                    cmdConn.send(xrg);
                    System.out.println("Polling SPOTs");
                } catch (IOException ex) {
                    Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
                }
                Utils.sleep(PAUSE);
            }
        }
    };

	/**
	 * Print out our radio address.
	 */
	public void run() {
		long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
		System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

		initDatabase();

		
		Radiogram rrg;
		try {
			cmdConn = (RadiogramConnection) Connector.open("radiogram://broadcast:"+CMD_PORT);
            cmdConn.setMaxBroadcastHops(0);
            xrg = (Radiogram) cmdConn.newDatagram(cmdConn.getMaximumLength());
            dataConn = (RadiogramConnection) Connector.open("radiogram://:"+ DATA_PORT);
			rrg = (Radiogram)dataConn.newDatagram(dataConn.getMaximumLength());
		} catch (IOException ex) {
			Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
			return;
		}

        pollThread.start();

        try {
			while (running) {
				dataConn.receive(rrg);
				System.out.println("Received packet");

				insert(rrg.getAddress(), rrg.readInt(), rrg.readDouble(), rrg.readDouble(), rrg.readDouble(), rrg.readLong());
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
        try {
            pollThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
        }
	}

	private void initDatabase() {
		try {
			// This finds the driver to connect to the MySQL database
			Class.forName("com.mysql.jdbc.Driver").newInstance();

			// Open a connection to the server, use database "database", with username "user" and password "pass"
			dbConn = DriverManager.getConnection("jdbc:mysql://" + DATABASE_HOST + "/" + DATABASE_NAME +
					"?user=" + DATABASE_USERNAME + "&password=" + DATABASE_PASSWORD);

			dbStmt = dbConn.createStatement();

			dbStmt.execute("CREATE TABLE IF NOT EXISTS kml_table (mac char(19), time bigint, light smallint, latitude numeric(15,13), longitude numeric(15,13), hdop numeric(2,1))");
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
			System.exit(1);
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
			System.exit(1);
		} catch (SQLException ex) {
			ex.printStackTrace();
			System.exit(1);
		} catch (InstantiationException ex) {
			ex.printStackTrace();
			System.exit(1);
		}
	}

	private void insert(String mac, int light, double lat, double lon, double hdop, long time) {
		try {
			String tuple = "('" + mac + "'," + light + "," + lat + "," + lon + "," + hdop + ", " + time + ")";
			System.out.println("(mac, light, lat, lon, hdop, time) = " + tuple);
            System.out.println("INSERT INTO kml_table (mac, light, latitude, longitude, hdop, time) VALUES " + tuple);
			dbStmt.execute("INSERT INTO kml_table (mac, light, latitude, longitude, hdop, time) VALUES " + tuple);
		} catch (SQLException ex) {
			Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public static void main(String[] args) {
		SunSpotHostApplication app = new SunSpotHostApplication();
		app.run();
	}
}
